/**
 * This is a fork of the UML2Java Plug-in developed by Topcased and released under
 * the Eclipse EPL License. http://www.eclipse.org/legal/epl-v10.html
 * In accordance with the license, I have forked the UML2Java plugin and have adapted
 * it to suit the needs of a UML2QoS instrumentation code generator for PHP.
 * 
 * @author Alexandru Burdusel
 */
package org.topcased.uml2qos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;


/**
 * Copies the QoS Framework to the project directory after the php files have been generated.
 * @author Alexandru Burdusel
 */
public class FrameworkGenerator {

	/**
	 * Copies the Aspect Oriented Framework from the org.topcased.uml2qos.generator/framework 
	 * folder to the project where the php classes directory is generated.
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static void copyFramework() throws URISyntaxException, IOException {
	
			File f = new File(FileLocator.toFileURL(Platform.getBundle("org.topcased.uml2qos.generator").getEntry("/")).toURI());
			File[] files = f.listFiles();

			for(int i = 0; i < files.length; i++){
				
				if(files[i].getName().equalsIgnoreCase("framework")){
					IFile file = GenQos.getModel();
					IPath path = file.getLocation().removeLastSegments(2);
					File trgDir = new File(path.toString()+GenQos.output);
					File srcDir = files[i];
					copy(srcDir, trgDir);
				}
			}
	}
	
   /**
    * Copies one directory to another directory
    * @param source
    * @param target
    * @throws IOException
    */
    public static void copy(File source , File target) throws IOException {
        
        if (source.isDirectory()) 
        {	
        	String[] subdirectoryEntities = source.list();
        	
            if (!target.exists()) {
            	target.mkdir();
            }

            for (int i=0; i<subdirectoryEntities.length; i++) {
            	copy(new File(source, subdirectoryEntities[i]), new File(target, subdirectoryEntities[i]));
            }
        } else {
            
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target);
            
            byte[] buf = new byte[1024];
            int peek = in.read(buf);
            
            while (peek > 0) {
                out.write(buf, 0, peek);
                peek = in.read(buf);
            }
            in.close();
            out.close();
        }
    } 
}